import m_contacts from '../mocks/contact';
import m_history from '../mocks/history';
import m_reply from '../mocks/reply';
import global from './global';
import define from '../define';
import moment from 'moment';
import MalasoonData from '../common/malasoon_data';
import durationFormat from 'moment-duration-format';

import wepy from 'wepy';

momentDurationFormatSetup(moment);

export default {
    async getUserInfo () {
        let info = global.userInfo;
        if (!info) {
            await wepy.login()
            let res = await wepy.getUserInfo()
            console.log('getuserinfo success');
            console.log(res)
            global.userInfo = res.userInfo
            info = res.userInfo;
        }
        return info;
    },

    waitMs(ms){
        return new Promise((resolve, reject) => {
            setTimeout(()=>{
                resolve();
            }, ms)
        })
    },

    wepyShowToast(title, icon, duration, mask)
    {
        return new Promise((resolve, reject)=>{
            wx.showToast({
                title: title,
                icon: icon,
                duration: duration,
                mask: mask,
                success: () => {
                    resolve();
                }
            })
        })
    },

    wepyShowLoading(title, mask)
    {
        return new Promise((resolve, reject)=>{
            wx.showLoading({
                title: title,
                mask: mask,
                success: () => {
                    resolve();
                }
            })
        })
    },

    async wepyHideLoading()
    {
        wx.hideLoading();
    },

    initRecords() {
        let info = wepy.getStorageInfoSync();
        console.log("[api]info:", info);
        let records = {};
        info.keys.forEach((k) => {
            if (k.indexOf(define.recordKey) !== -1) {
                let record = wepy.getStorageSync(k);
                records[record.id] = this.recordFormat(record, "read");
            }
        });
        global.records = records;
    },

    _getRecordIcon(record){
        return "../mocks/users/ertai.png";
    },

    async saveRecord(record) {
        global.records[record.id] = record;
        if (!this.getMalasoonData(record.name))
        {
            global.malasoonDatas[record.name] = {name:record.name, place:record.place, icon:record.icon};
            console.log('[api] global data ', global.malasoonDatas);
            global.userDefine[record.name] = global.malasoonDatas[record.name];
            this.saveUserDefine(global.userDefine);
        }
        return this.saveRecordToDataBase(record);
    },

    async deleteRecord(id) {
        delete global.records[id];
        return this.removeRecordFromDataBase(id);
    },

    recordFormat(record, way) {
        let format = {
            date: {
                write: (v) => {
                    return v.format('YYYY/MM/DD');
                },
                read: (v) => {
                    return moment(v, 'YYYY/MM/DD');
                },
                show: (v) => {
                    return v.format('YYYY/MM/DD');
                }
            },
            timeScore: {
                write: (v) => {
                    return v.format("h:mm:ss")
                },
                read: (v) => {
                    return moment.duration(v);
                },
                show: (v) => {
                    return v.format("h:mm:ss")
                },
            }
        }
        let fdata = {};
        for (let k in record) {
            let funcs = format[k] || {};
            let func = funcs[way];
            // console.log("[api]:", k, way, func)
            fdata[k] =  func ? func(record[k]): record[k];
        }
        // console.log("[api]:", fdata);
        return fdata;
    },

    async saveUserDefine(userDefine) {
        return wepy.setStorage({
            key: define.userDefineKey,
            data: userDefine 
        });
    },


    async saveRecordToDataBase(record) {
        record = this.recordFormat(record, "write");
        console.log("[api] format-reocrd:", record);
        return wepy.setStorage({
            key: define.recordKey + record.id,
            data: record 
        });
    },


    async removeRecordFromDataBase(id) {
        return wepy.removeStorage({
            key: define.recordKey + id,
        });
    },

    getTimeMinute(timeScore) {
        let time_array = timeScore.split(":")
        return Number(time_array[0])*60 + Number(time_array[1])
    },

    initUid() {
        global.uid = wepy.getStorageSync(define.uidKey) || 1;
    },

    async genUid() {
        let uid = global.uid;
        global.uid += 1;
        return wepy.setStorage({
                 key: define.uidKey,
                 data: global.uid 
             });
    },

    getMapValues(mp) {
        let list = [];
        for (let k in mp) {
            list.push(mp[k]);
        }
        return list;
    },

    genRandomData(num) {
        let records = {};
        for (i = 0; i< num; ++i) {
            let record = {};
            record.id = this.genUid();
            record.name = mdata.name;
            record.place = this.getMalasoonPlace(this.mdata.place);
            record.playerId = Math.floor(Math.random()*1000);
            let year = Math.floor(Math.random()*4 + 2015) 
        }

    },

    getMalasoonPlace(place) {
        
        if (place.country === '中国') {
            if (place.province === '') {
                return place.country + place.city;
            } else {
                return place.province + place.city;
            }
        } else {
            return place.country + place.city;
        }
    },

    initMalasoonData() {
        global.malasoonDatas = {};
        for (let k in MalasoonData) {
            let data = MalasoonData[k]
            global.malasoonDatas[k] = {name:k, place:this.getMalasoonPlace(data.place), icon:(data.icon||'')}
        }
        let userDefine = wepy.getStorageSync(define.userDefineKey) || {}; 
        for (let k in userDefine)
        {
            global.malasoonDatas[k] = userDefine[k];
        }
        console.log("[api:initMalasoonData]", global.malasoonDatas);
        global.userDefine = userDefine;
    },

    getMalasoonData(name) {
        return name ? global.malasoonDatas[name] : global.malasoonDatas;
    },

    initSystemInfo() {
        let res = wx.getSystemInfoSync();
        global.windowWidth = res.windowWidth;
        global.windowHeight = res.windowHeight;
    },

    getIconPath(iconName) {
        return `/images/icons/${iconName}.png`;
    },

    // 获取一个地址的经纬度
    getPlaceLocation(place) {
        let googleMap = global.googleMap;
        return wepy.request({
            url:`https://${googleMap.url}/json?address==${place}&key=${googleMap.appKey}`
        }).then((res) => {
            let data = res.data
            console.log("google_data")
            if (data.status != "OK" ) {
                console.log(`get place ${place} location failed`)
                return 
            }
            if (data.results.length > 0) {
                console.log(`place ${place} more than one ${data.results}`)
            }
            // result里有很多信息，可以log查看
            let result = data.results[0];
            console.log(result);
            return result.geometry.location;
        })
    },

    // 获得天气 longtitude --经度  latitude--纬度
    getLocationWeather(location, unixTime) {
        console.log("lc wt", location, unixTime);
        let darkSky = global.darkSky;
        return wepy.request({
            url:`https://${darkSky.url}/${darkSky.appKey}/${location.lat},${location.lng}, ${unixTime}?exclude=currently, flags, daily&lang=zh`
        }).then((res) => {
            return res;
        })

    }
}
